<template>
    <div class="app-container">
      <!-- 搜索条件 -->
        <a-form :model="queryParams" ref="queryForm" size="small" layout="inline">
            <a-row type="flex">
                <a-col :span="5">
                    <a-form-item label="执行器" prop="jobGroup">
                        <a-select v-model="queryParams.jobGroup" placeholder="全部" style="width: 150px;">
                            <a-select-option v-for="item in actuator_options" :key="item.value" :label="item.label" :value="item.value">
                                {{ item.label }}
                            </a-select-option>
                        </a-select>
                    </a-form-item>
                </a-col>
                <a-col :span="3">
                    <a-form-item label="任务">
                        <a-select v-model="task" style="width: 80px;">
                            <a-select-option value="0">全部</a-select-option>
                        </a-select>
                    </a-form-item>
                </a-col>
                <a-col :span="3">
                    <a-form-item label="状态" prop="logStatus">
                        <a-select v-model="queryParams.logStatus" style="width: 100px;">
                            <a-select-option value="-1">全部</a-select-option>
                            <a-select-option value="1">成功</a-select-option>
                            <a-select-option value="2">失败</a-select-option>
                            <a-select-option value="3">进行中</a-select-option>
                        </a-select>
                    </a-form-item>
                </a-col>
                <a-col>
                    <a-form-item label="调度时间">
                        <a-range-picker
                        showTime
                        v-model="dateRange"
                        format="yyyy-MM-DD HH:mm:ss"
                        :ranges="pickerOptions"
                        :placeholder="['开始时间', '结束时间']"
                        ></a-range-picker>
                    </a-form-item>
                </a-col>
                <a-col>
                    <a-form-item>
                        <a-button type="primary" icon="search" @click="handleQuery">搜索</a-button>
                        <a-button icon="delete" @click="clearlog">清理</a-button>
                    </a-form-item>
                </a-col>
            </a-row>
        </a-form>

        <!--select控制一个页面展示多少条-->
    <div>每页
      <a-select default-value="10" style="width: 80px" @change="handlePageSizeChange">
        <a-select-option value="10">
          10
        </a-select-option>
        <a-select-option value="20">
          20
        </a-select-option>
        <a-select-option value="30">
          30
        </a-select-option>
        <a-select-option value="50">
          50
        </a-select-option>
        <a-select-option value="100">
          100
        </a-select-option>
      </a-select>
      条记录
    </div>

    <!-- 表格数据 -->
    <a-table v-loading="loading" :columns="columns" :dataSource="logList" :pagination="false" :rowKey="record=>record.id">
        <span slot="triggerTime" slot-scope="text,record">
            {{ record.triggerTime | dateFormat }}
        </span>
        <span slot="triggerCode" slot-scope="text,record">
            <span v-if="record.triggerCode==500" style="color: red;">失败</span>
            <span v-else style="color: green;">成功</span>
        </span>
        <span slot="triggerMsg" slot-scope="text,record">
          <a-button type="link" @click="stateFormat(record)">查看</a-button>
        </span>
        <span slot="handleTime" slot-scope="text,record">
          <span v-if="record.handleTime==''||record.handleTime==null"></span>
          <span v-else>{{ record.handleTime | dateFormat }}</span>
        </span>
        <span slot="handleCode" slot-scope="text,record">
          <span v-if="record.handleCode==0"></span>
            <span v-else-if="record.handleCode==200" style="color: green;">成功</span>
            <span v-else style="color: red;">失败</span>
        </span>
        <span slot="handleMsg" slot-scope="text,record">
          <span v-if="record.handleMsg==null||record.handleMsg==''">无</span>
          <span v-else><a-button type="link" @click="state(record)">查看</a-button></span>
        </span>
        <span slot="action" slot-scope="text, record">
          <span v-if="record.triggerCode==500"></span>
          <span v-else-if="record.handleCode==0">
            <a-dropdown-button type="primary">操作
                  <a-menu slot="overlay" >
                      <a-menu-item>
                        <router-link :to="'/xxl-job/joblog/logDetailPage/' + record.id" class="link-type">
                        <span>执行日志</span>
                      </router-link>
                      </a-menu-item>
                      <a-menu-item @click="stoplog(record.id)">终止任务</a-menu-item>
                  </a-menu>
                  <a-icon slot="icon" type="down" />
              </a-dropdown-button>
            </span>
            <span v-else>
              <a-dropdown-button type="primary">操作
                  <a-menu slot="overlay" >
                      <a-menu-item>
                        <router-link :to="'/xxl-job/joblog/logDetailPage/' + record.id" class="link-type">
                        <span>执行日志</span>
                      </router-link>
                      </a-menu-item>
                  </a-menu>
                  <a-icon slot="icon" type="down" />
              </a-dropdown-button>
            </span>
          </span>
    </a-table>

    <!-- 下方分页 -->
    <a-pagination v-model="pagination.current" :item-render="pagination.itemRender" :total="pagination.total"
      :page-size="pagination.pageSize"
      :show-total="(total) => `共 ${total} 条（总共${Math.ceil(total / this.pagination.pageSize)}页, ${total} 条记录）`"
      :page-size-options="pagination.pageSizeOptions" @change="handlePageChange">
    </a-pagination>

      <!-- 查看调度备注 -->
      <a-modal :title="title" width="20%" v-model:visible="check">
        <span v-html="Trimsg"></span>
        <div slot="footer" class="dialog-footer">
          <a-button type="primary" @click="check = false">确定</a-button>
        </div>
      </a-modal>

      <!-- 查看执行备注 -->
      <a-modal :title="title" width="20%" v-model:visible="checkhandle">
        <span>{{ hanMsg }}</span>
        <div slot="footer" class="dialog-footer">
          <a-button type="primary" @click="checkhandle = false">确定</a-button>
        </div>
      </a-modal>

      <!-- 日志清理对话框 -->
      <a-modal :title="title" width="450px" v-model:visible="clear">
        <a-form-model ref="form" :model="form" layout="horizontal" :label-col="{ span: 5 }" :wrapper-col="{ span:19 }">
            <a-form-model-item label="执行器">
            <a-select :disabled=true v-model:value="form.jobGroup">
            <a-select-option :value="0">全部</a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="任务">
            <a-select :disabled=true v-model:value="form.jobId">
            <a-select-option :value="0">全部</a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="清理方式">
            <a-select v-model:value="form.type">
            <a-select-option :value="1">清理一个月之前日志数据</a-select-option>
            <a-select-option :value="2">清理三个月之前日志数据</a-select-option>
            <a-select-option :value="3">清理六个月之前日志数据</a-select-option>
            <a-select-option :value="4">清理一年之前日志数据</a-select-option>
            <a-select-option :value="5">清理一千条以前日志数据</a-select-option>
            <a-select-option :value="6">清理一万条以前日志数据</a-select-option>
            <a-select-option :value="7">清理三万条以前日志数据</a-select-option>
            <a-select-option :value="8">清理十万条以前日志数据</a-select-option>
            <a-select-option :value="9">清理所有日志数据</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-form-model>
        <div slot="footer" class="dialog-footer">
          <a-button type="primary" @click="handleClean">确定</a-button>
          <a-button @click="cancel">取消</a-button>
        </div>
      </a-modal>
    </div>
</template>
<script>
  import { listLog, CleanLog,Stoptask } from "@/api/xxl-job/log";
  import { listGroup } from "@/api/xxl-job/group";
  // 引入moment组件
  import moment from 'moment';
  
  export default {
    name: "AntDesignLog",
    filters: {
        dateFormat:function(time,pattern="YYYY-MM-DD HH:mm:ss"){
            return moment(time).format(pattern)
        }
  },
    data() {
      return {
        //搜索条件全部任务
        task:"0",
        //终止任务
        stopid:{
          id:0,
        },
        //选择调度时间
        pickerOptions: {
            最近一小时:[moment().subtract(1, "hours"),moment()],
            今日: [moment().startOf('day'), moment().endOf('day')],
            昨日:[moment().subtract(1, 'day').startOf('day'),moment().subtract(1, 'day').endOf('day')],
            本月:[moment().startOf('months'),moment().endOf('months')],
            上个月:[ moment().subtract(1, 'months').startOf('months'),moment().subtract(1, 'months').endOf('months')],
            最近一周:[moment().subtract(1, 'week').startOf('day'),moment().endOf('day')],
            最近一月:[moment().subtract(1, 'months').startOf('day'),moment().endOf('day')]
        },
        //执行备注
        hanMsg:'',
        //调度备注
        Trimsg:'',
        //日期范围
        dateRange:[],
        // 排序 每页最新的在上面
        defaultSort: {prop: 'triggerTime', order: 'descending'},
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 总条数
        total: 0,
        // 表格数据
        logList: [],
        // 获取的执行器数据
        grouplist: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        check:false,
        checkhandle:false,
        clear:false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          id:null,
          jobGroup: null,
          jobId: null,
          executorAddress: null,
          executorHandler: null,
          executorParam: null,
          executorShardingParam: null,
          executorFailRetryCount: null,
          triggerTime: null,
          triggerCode: null,
          triggerMsg: null,
          handleTime: null,
          handleCode: '',
          handleMsg: null,
          alarmStatus: null,
          logStatus:'-1',
        },
        //表格内容
    columns: [{
      title: '任务ID',
      dataIndex: 'jobId',
      key: 'jobId',
      align:'center',
    },
    {
      title: '调度时间',
      dataIndex: 'triggerTime',
      key: 'triggerTime',
      align:'center',
      scopedSlots: { customRender: 'triggerTime' },
    },
    {
      title: '调度结果',
      dataIndex: 'triggerCode',
      key: 'triggerCode',
      align:'center',
      scopedSlots: { customRender: 'triggerCode' },
    },
    {
      title: '调度备注',
      dataIndex: 'triggerMsg',
      key: 'triggerMsg',
      align:'center',
      scopedSlots: { customRender: 'triggerMsg' },
    },
    {
      title: '执行时间',
      dataIndex: 'handleTime',
      key: 'handleTime',
      align:'center',
      scopedSlots: { customRender: 'handleTime' },
    },
    {
      title: '执行结果',
      dataIndex: 'handleCode',
      key: 'handleCode',
      align:'center',
      scopedSlots: { customRender: 'handleCode' },
    },
    {
      title: '执行备注',
      dataIndex: 'handleMsg',
      key: 'handleMsg',
      align:'center',
      scopedSlots: { customRender: 'handleMsg' },
    },
    {
      title: '操作',
      scopedSlots: { customRender: 'action' },
      align:'center',
    }],
    //pagination分页参数
    pagination: ({
        pageSize: 10, // 每页显示的条数
        showQuickJumper: false, // 是否可以快速跳转到指定页
        current: 1, // 当前页数
        total: 50, // 总条数
        itemRender(current, type, originalElement) {
          if (type === 'prev') {
            return <div style="padding-left:850px"><a>上页</a></div>;
          } else if (type === 'next') {
            return <a>下页</a>;
          }
          return originalElement;
        },
      }),
        // 表单参数
        form: {},
        actuator_options: [],
      };
    },
    created() {
      this.getList();
    },
    mounted() {
    this.getGroup()
    },
    methods: {
        /* 页码改变时的处理函数*/
    handlePageChange(page, pageSize) {
      this.queryParams.pageNum = page
      this.pagination.current = page
      this.getList()
    },
        /* 页码改变时的处理函数*/
    handlePageSizeChange(page) {
      this.queryParams.pageSize = page
      this.pagination.pageSize = page
      this.getList()
    },
      //终止任务
      stoplog(id){
         this.stopid.id=id
        this.$modal.confirm("确认终止任务吗？").then(()=>{
          return Stoptask(this.stopid)
        }).then(response=>{
                this.$modal.msgSuccess("终止成功");
                this.getList();
          }).catch(() => {
              });
      },
        //打开清理日志
        clearlog(){
            this.reset();
            this.clear=true
            this.title='日志清理'
        },
        // 获取执行器数据
    getGroup() {
      this.loading = true;
      listGroup(this.queryParams).then(response => {
        this.groupList = response.rows;
        for (let item in this.groupList) {
          this.actuator_options.push({
            value: this.groupList[item].id,
            label: this.groupList[item].title
          })
        }
        this.loading = false;
      });
    },
      //查看执行备注
      state(row){
        this.hanMsg=row.handleMsg
        this.checkhandle=true
      },
      //查看调度备注
      stateFormat(row){
        this.Trimsg=row.triggerMsg
        this.check=true
      },
      /* 查询列表 */
      getList() {
        this.loading = true;
        listLog(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.logList = response.rows;
          this.pagination.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.clear = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          jobGroup:0,
          jobId:0,
          type:1,
        };
        this.resetForm("form");
      },
      /* 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        //时间格式转换
        if(this.dateRange[0]!=this.dateRange[1]){
          this.dateRange[0]=moment(this.dateRange[0]).format('YYYY-MM-DD HH:mm:ss')
          this.dateRange[1]=moment(this.dateRange[1]).format('YYYY-MM-DD HH:mm:ss')
        }
        this.getList();
      },
      //清理日志
      handleClean:function(){
        this.$refs["form"].validate(valid => {
          if(valid){
            CleanLog(this.form).then(response => {
                this.$modal.msgSuccess("清理成功");
                this.clear = false;
                this.getList();
              })
          }
        });
      },
    }
  };
  </script>